﻿
using System;
using System.ComponentModel;
using System.Configuration;
using System.IO;


namespace BoilenEditor.Primitives {

    public sealed partial class SettingPropertyData {

        private object originalValue_;
        private TypeConverter converter_;


        partial void InitializeInstance( ) {
            this.originalValue_ = this.Setting.PropertyValue;
            this.converter_ = TypeDescriptor.GetConverter( this.PropertyType );

            this.SerializedValue = (string)this.Setting.SerializedValue;
        }


        public string Name {
            get { return this.Setting.Name; }
        }

        public Type PropertyType {
            get { return this.Setting.Property.PropertyType; }
        }

        public object Value {
            get { return this.Setting.PropertyValue; }
            private set {
                this.Setting.PropertyValue = value;
                this.OnPropertyChanged( "Value" );

                bool isDirty = !object.Equals( value, this.originalValue_ );
                this.IsDirty = isDirty;
            }
        }

        public bool IsDirty {
            get { return !object.Equals( this.Value, this.originalValue_ ); }
            private set {
                this.Setting.IsDirty = value;
                this.OnPropertyChanged( "IsDirty" );
            }
        }


        partial void SerializedValueChanged( string oldValue ) {
            string serializedValue = this.SerializedValue;
            this.Setting.SerializedValue = serializedValue;

            object value = this.converter_.ConvertFromInvariantString( serializedValue );

            string path = value as string;
            if( path.HasValue( ) && this.Name.EndsWith( "Path" ) && !File.Exists( path ) ) {
                if( path.StartsWith( "\"" ) || path.EndsWith( "\"" ) )
                    this.SerializedValue = path.TrimStart( '"' ).TrimEnd( '"' );
                else
                    throw new FileNotFoundException( "Could not find the specified file.", path );
            }

            this.Value = value;
        }

        private static string GetOriginalSerializedValue( SettingsPropertyValue setting ) {
            return (string)setting.SerializedValue;
        }

    }

}
